// 云函数入口文件
const cloud = require('wx-server-sdk')
const ExcelJS = require('exceljs')
const fs = require('fs')
const path = require('path')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 下载云存储文件到本地临时目录
async function downloadFileToLocal(fileId, fileName) {
  try {
    console.log(`开始下载文件: ${fileId}`);
    
    // 检查fileId格式
    if (!fileId || typeof fileId !== 'string') {
      throw new Error(`无效的文件ID: ${fileId}`);
    }
    
    // 获取文件内容
    const fileResult = await cloud.downloadFile({
      fileID: fileId
    });
    
    console.log(`文件下载响应:`, {
      hasFileContent: !!fileResult.fileContent,
      contentLength: fileResult.fileContent ? fileResult.fileContent.length : 0
    });
    
    if (!fileResult.fileContent) {
      throw new Error('下载的文件内容为空');
    }
    
    // 保存到临时目录
    const tempPath = path.join('/tmp', fileName);
    fs.writeFileSync(tempPath, fileResult.fileContent);
    
    // 验证文件是否写入成功
    if (!fs.existsSync(tempPath)) {
      throw new Error(`文件写入失败: ${tempPath}`);
    }
    
    const fileStats = fs.statSync(tempPath);
    console.log(`文件下载成功: ${fileId} -> ${tempPath}, 大小: ${fileStats.size} bytes`);
    return tempPath;
  } catch (error) {
    console.error(`下载文件失败: ${fileId}`, {
      message: error.message,
      stack: error.stack,
      fileId: fileId,
      fileName: fileName
    });
    throw error;
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { params } = event
  
  const generateUniqueId = () => {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000);
    return `${timestamp}_${random}`;
  };
  const uuid = generateUniqueId()
  // 修复：统一使用 /tmp 目录（云函数环境的临时目录）
  const excelPath = path.join('/tmp', `${uuid}.xlsx`)
  
  // 需要清理的临时文件列表
  const tempFiles = [excelPath];
  
  try {
    await createExcel(params, excelPath)
    
    // 等待Excel文件创建完成
    while(!fs.existsSync(excelPath) || fs.statSync(excelPath).size === 0) {
      console.log("等待Excel创建完成")
      await new Promise(resolve => setTimeout(resolve, 1000))
    }
    
    const getYearMonth =  function() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需 +1
      return `${year}${month}`;
    }
    const fileBuffer = fs.readFileSync(excelPath)
    const uploadResult = await cloud.uploadFile({
      cloudPath: `motor_images/${getYearMonth()}/${uuid}.xlsx`, 
      fileContent: fileBuffer, 
    })

    // 清理所有临时文件
    cleanupTempFiles(tempFiles);
    
    return {
      success: true,
      fileID: uploadResult.fileID,
      message: "Excel生成并上传成功"
    }
    
  } catch (error) {
    console.error("处理失败:", error)
    // 确保清理临时文件
    cleanupTempFiles(tempFiles);
    
    return {
      success: false,
      error: error.message
    }
  }
}

// 清理临时文件
function cleanupTempFiles(fileList) {
  // 清理Excel文件
  fileList.forEach(filePath => {
    try {
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
        console.log(`临时文件已清理: ${filePath}`);
      }
    } catch (err) {
      console.log(`清理临时文件失败: ${filePath}`, err);
    }
  });
  
  // 清理可能的图片文件
  try {
    const image1Path = '/tmp/image1.png';
    const image2Path = '/tmp/image2.png';
    
    if (fs.existsSync(image1Path)) {
      fs.unlinkSync(image1Path);
      console.log('临时图片1已清理');
    }
    
    if (fs.existsSync(image2Path)) {
      fs.unlinkSync(image2Path);
      console.log('临时图片2已清理');
    }
  } catch (err) {
    console.log('清理图片文件失败:', err);
  }
}

// 创建Excel文件
async function createExcel(params, excelPath) {
  try {
    // 默认变量值
    const defaultVariables = {
      date: new Date().toLocaleDateString('zh-CN'),
      action: "电机选型报告",
      company_name: "未知",
      name: "访客用户", 
      phone: "未知",
      image1_url: null,
      image2_url: null, 
      results: "计算结果将在此显示"
    }
    
    // 处理图片文件ID，下载到本地临时文件
    if (params.image1_fileId) {
      try {
        const image1Path = await downloadFileToLocal(params.image1_fileId, 'image1.png');
        params.image1_url = image1Path;
        console.log('图片1下载成功:', params.image1_url);
      } catch (error) {
        console.error('下载图片1失败:', error);
        params.image1_url = null;
      }
    }

    if (params.image2_fileId) {
      try {
        const image2Path = await downloadFileToLocal(params.image2_fileId, 'image2.png');
        params.image2_url = image2Path;
        console.log('图片2下载成功:', params.image2_url);
      } catch (error) {
        console.error('下载图片2失败:', error);
        params.image2_url = null;
      }
    }
    
    // 合并传入的参数和默认变量
    const variables = Object.assign(defaultVariables, params || {})
    console.log('最终变量:', variables);
    
    // 创建工作簿
    const workbook = new ExcelJS.Workbook();
    
    // 只创建一个工作表
    const worksheet = workbook.addWorksheet('电机选型报告', {
      pageSetup: {
        paperSize: 9, // A4
        orientation: 'portrait',
        margins: {
          left: 0.7,
          right: 0.7,
          top: 0.75,
          bottom: 0.75,
          header: 0.3,
          footer: 0.3
        }
      },
      views: [{
        showGridLines: false,  // 隐藏网格线
        showRowColHeaders: false  // 隐藏行列标题
      }]
    });

    // 移除默认工作表（如果存在多个）
    while (workbook.worksheets.length > 1) {
      workbook.removeWorksheet(workbook.worksheets[0].id);
    }

    // 设置列宽 - 8列布局
    worksheet.columns = [
      { width: 12 },
      { width: 12 },
      { width: 12 },
      { width: 12 },
      { width: 12 },
      { width: 12 },
      { width: 12 },
      { width: 12 }
    ];

    // 移除所有单元格的边框，确保背景完全像白纸
    const removeAllBorders = () => {
      worksheet.eachRow((row, rowNumber) => {
        row.eachCell((cell, colNumber) => {
          cell.border = {};
        });
      });
    };

    let currentRow = 1;

    // 空行用于页面顶部间距
    currentRow += 3;

    // 公司标题
    worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
    const companyTitleCell = worksheet.getCell(`A${currentRow}`);
    companyTitleCell.value = '欣致元智能科技（上海）有限公司';
    companyTitleCell.font = { size: 26, bold: true };
    companyTitleCell.alignment = { horizontal: 'center', vertical: 'middle' };
    worksheet.getRow(currentRow).height = 40;
    currentRow++;

    // 空行
    currentRow++;

    // 日期
    worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
    const dateCell = worksheet.getCell(`A${currentRow}`);
    dateCell.value = variables.date;
    dateCell.font = { size: 12 };
    dateCell.alignment = { horizontal: 'center', vertical: 'middle' };
    worksheet.getRow(currentRow).height = 20;
    currentRow++;

    // 空行
    currentRow++;

    // 添加公司Logo - 保持原始比例并放大
    const logoPath = path.join(__dirname, 'logo.jpg');
    if (fs.existsSync(logoPath)) {
      try {
        const logoId = workbook.addImage({
          filename: logoPath,
          extension: 'jpeg',
        });
        
        // 保持原始比例，放大logo
        worksheet.addImage(logoId, {
          tl: { col: 2.5, row: currentRow - 1 }, // 居中显示
          br: { col: 5.5, row: currentRow + 6 } // 使用tl和br来保持比例
        });
        
        console.log('Logo添加成功');
      } catch (error) {
        console.error('添加Logo失败:', error);
      }
    }

    // 为Logo预留更多空间
    for (let i = 0; i < 8; i++) {
      worksheet.getRow(currentRow + i).height = 20;
    }
    currentRow += 8;

    // 空行
    currentRow += 3;

    // 分隔线（使用字符）
    worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
    const separatorCell1 = worksheet.getCell(`A${currentRow}`);
    separatorCell1.value = '————————————————————————————————————————';
    separatorCell1.alignment = { horizontal: 'center', vertical: 'middle' };
    separatorCell1.font = { size: 14 };
    currentRow++;

    worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
    const separatorCell2 = worksheet.getCell(`A${currentRow}`);
    separatorCell2.value = '————————————————————————————————————————';
    separatorCell2.alignment = { horizontal: 'center', vertical: 'middle' };
    separatorCell2.font = { size: 14 };
    currentRow++;

    // 空行
    currentRow += 2;

    // 报告标题
    worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
    const titleCell = worksheet.getCell(`A${currentRow}`);
    titleCell.value = variables.action || '电机选型报告';
    titleCell.font = { size: 18, bold: true };
    titleCell.alignment = { horizontal: 'center', vertical: 'middle' };
    worksheet.getRow(currentRow).height = 30;
    currentRow++;

    // 空行
    currentRow += 4;

    // 客户信息标题
    worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
    const infoHeaderCell = worksheet.getCell(`A${currentRow}`);
    infoHeaderCell.value = '客户信息';
    infoHeaderCell.font = { size: 16, bold: true };
    infoHeaderCell.alignment = { horizontal: 'left', vertical: 'middle' };
    worksheet.getRow(currentRow).height = 25;
    currentRow++;

    // 空行
    currentRow++;

    // 客户信息内容
    const customerInfo = [
      `• 公司名称: ${variables.company_name}`,
      `• 姓名: ${variables.name}`,
      `• 联系电话: ${variables.phone}`
    ];

    customerInfo.forEach(info => {
      worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
      const infoCell = worksheet.getCell(`A${currentRow}`);
      infoCell.value = info;
      infoCell.font = { size: 12, bold: true };
      infoCell.alignment = { horizontal: 'left', vertical: 'middle' };
      worksheet.getRow(currentRow).height = 25;
      currentRow++;
    });

    // 空行
    currentRow += 3;

    // 电机选型计算标题
    worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
    const calcHeaderCell = worksheet.getCell(`A${currentRow}`);
    calcHeaderCell.value = '1. 电机选型计算';
    calcHeaderCell.font = { size: 16, bold: true };
    calcHeaderCell.alignment = { horizontal: 'left', vertical: 'middle' };
    worksheet.getRow(currentRow).height = 25;
    currentRow++;

    // 空行
    currentRow++;

    // 独立运动曲线标题
    worksheet.mergeCells(`A${currentRow}:H${currentRow}`);
    const curveHeaderCell = worksheet.getCell(`A${currentRow}`);
    curveHeaderCell.value = '1.1 独立运动曲线';
    curveHeaderCell.font = { size: 14, bold: true };
    curveHeaderCell.alignment = { horizontal: 'left', vertical: 'middle' };
    worksheet.getRow(currentRow).height = 22;
    currentRow++;

    // 空行
    currentRow++;

    // 图片和结果布局 - 左侧图片，右侧结果
    const imageStartRow = currentRow;
    let totalImageRows = 0;
    
    // 添加图片到左侧 (A-D列)
    if (variables.image1_url && fs.existsSync(variables.image1_url)) {
      try {
        const imageId1 = workbook.addImage({
          filename: variables.image1_url,
          extension: 'png',
        });
        
        worksheet.addImage(imageId1, {
          tl: { col: 0, row: currentRow - 1 }, // 从A列开始
          ext: { width: 280, height: 180 }
        });
        
        console.log('图片1添加成功');
      } catch (error) {
        console.error('添加图片1失败:', error);
      }
    }

    // 为第一张图片预留空间
    const image1Rows = 12;
    for (let i = 0; i < image1Rows; i++) {
      worksheet.getRow(currentRow + i).height = 18;
    }
    currentRow += image1Rows;
    totalImageRows += image1Rows;

    if (variables.image2_url && fs.existsSync(variables.image2_url)) {
      try {
        const imageId2 = workbook.addImage({
          filename: variables.image2_url,
          extension: 'png',
        });
        
        worksheet.addImage(imageId2, {
          tl: { col: 0, row: currentRow - 1 }, // 从A列开始
          ext: { width: 280, height: 180 }
        });
        
        console.log('图片2添加成功');
      } catch (error) {
        console.error('添加图片2失败:', error);
      }
    }

    // 为第二张图片预留空间
    const image2Rows = 12;
    for (let i = 0; i < image2Rows; i++) {
      worksheet.getRow(currentRow + i).height = 18;
    }
    totalImageRows += image2Rows;

    // 在右侧添加计算结果 (E-H列)
    // 如果没有图片，至少预留15行给结果显示
    const minResultRows = 15;
    const resultRows = Math.max(totalImageRows, minResultRows);
    
    worksheet.mergeCells(`E${imageStartRow}:H${imageStartRow + resultRows - 1}`);
    const resultsCell = worksheet.getCell(`E${imageStartRow}`);
    resultsCell.value = variables.results || '计算结果将在此显示';
    resultsCell.alignment = { horizontal: 'left', vertical: 'top', wrapText: true };
    // 移除背景色，保持纯白背景
    resultsCell.font = { size: 11 };

    // 在保存前移除所有边框
    removeAllBorders();
    
    // 保存Excel文件
    await workbook.xlsx.writeFile(excelPath);
    console.log("Excel文件创建成功: " + excelPath);
    
  } catch (error) {
    console.error("createExcel异常:", error);
    throw error;
  }
}